import java.util.Arrays;

public class Solution1423 {
    public int maxScore(int[] cardPoints, int k) {
        int windowLen= cardPoints.length-k;
        int windowMin=0;
        int windowVal=0;
        for (int i = 0; i <= cardPoints.length-windowLen; i++) {
            if(i==0){
                for (int j = i; j < i+windowLen; j++) {
                    windowVal+=cardPoints[j];
                }
            }
            else {
                windowVal-=cardPoints[i-1];
                windowVal+=cardPoints[i+windowLen-1];
            }
            if(windowMin>windowVal||windowMin==0){
                windowMin=windowVal;
            }
        }
        return Arrays.stream(cardPoints).sum()-windowMin;
    }
}
